
import mraa


# 0x10 ~ 0x17: ADC raw data
# 0x20 ~ 0x27: input voltage
# 0x29: output voltage / Grove power supply voltage


class ADC(object):
    bus = None

    def __init__(self):
        if ADC.bus is None:
            ADC.bus = mraa.I2c(0)

        self.bus.address(0x04)
        
    def read_raw(self, channel):
        addr = 0x10 + channel
        return self.read_register(addr)

    # read input voltage (mV)
    def read_voltage(self, channel):
        addr = 0x20 + channel
        return self.read_register(addr)

    def read(self, channel):
        addr = 0x30 + channel
        return self.read_register(addr)

    @property
    def name(self):
        id = self.read_register(0x0)
        if id == 0x4:
            return 'Grove Base HAT RPi'
        elif id == 0x5:
            return 'Grove Base HAT RPi Zero'

    @property
    def version(self):
        return self.read_register(0x3)

    # read 16 bits register
    def read_register(self, addr):
        self.bus.writeByte(addr)
        return self.bus.readWordReg(addr)


if __name__ == '__main__':
    import time

    adc = ADC()
    while True:
        print(adc.read_voltage(0))
        time.sleep(1)

    
    
